package com.smasher.camera.analyzer

import android.annotation.SuppressLint
import android.util.Log
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage

/**
 * recognize qrcode using
 * [google ML kit](https://developers.google.com/ml-kit/vision/barcode-scanning/android)
 * @author ivan200 [link](https://github.com/ivan200)
 * @desc
 * @since 2021-01-08
 */
class MLQRcodeAnalyzer(private val resultHandler: (String) -> Unit) : ImageAnalysis.Analyzer {
    //private val fpsDelegate = FpsDelegate()

    private val scanner: BarcodeScanner by lazy {
        BarcodeScanning.getClient(
            BarcodeScannerOptions.Builder()
                .setBarcodeFormats(Barcode.FORMAT_QR_CODE)
                .build()
        )
    }


    @SuppressLint("UnsafeExperimentalUsageError", "UnsafeOptInUsageError")
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            //fpsDelegate.tick()
            scanner.process(image)
                .addOnSuccessListener {
                    resultHandler.invoke(it.joinToString { barcode -> barcode?.rawValue.toString() })
                }
                .addOnFailureListener {
                    Log.e(TAG, "analyze: ${it.message}")
                }
                .addOnCompleteListener {
                    imageProxy.close()
                }
        }
    }

    companion object {
        const val TAG = "Analyzer"
    }
}